package dabs.ginterface;

import dabs.engine.*;
import dabs.engine.control.GameCommand;
import dabs.engine.control.ReadCommand;
import dabs.engine.exceptions.ComponentNotFoundException;
import dabs.engine.exceptions.UnknownGameCommand;
import dabs.engine.messaging.Notification;
import dabs.engine.messaging.NotificationHandler;

import java.io.*;



public class GameInterface implements Runnable, NotificationHandler {
	private GameEngine geng;
	private CommandParser parser; 
	
	public GameInterface(GameEngine geng) {
		this.geng = geng;
		this.parser = new CommandParser();
		geng.registerInterface(this);
	}

	synchronized public void handleNotification(Notification notif) {
		if (notif.getSource().isEmpty()) {
			System.out.println(notif.getDescription());
		} else {
			System.out.println(notif.getSource() + ": " + notif.getDescription());
		}
		
	}

	// process a single command;
	private void processCommand(String command) {
		if (command.isEmpty())
			return;
		
		try {
			geng.runCommand(new GameCommand(command.trim()));
			return; // if above executes, we don't need to check anything else
		} catch (UnknownGameCommand e) {
			// do nothing
		}

		// if powerplant is not running then we don't process other commands
		// and we're not in debug mode
		if ( geng.getState() != GameState.Running && !geng.inDebugMode() ) { 
			return;
		}
		
		if (parser.type(command).equals("componentcommand")) {
			try {
				geng.getOperatorSoftware().runCommand(parser.asComponentCommand(command));
			} catch (ComponentNotFoundException e) {
				System.out.println(e);
			}
		
		} else if (parser.type(command).equals("read")) {
			ReadCommand rc = parser.asReadCommand(command);
			try {
				if (rc.getAttribute() == "") {
					System.out.println(geng.getPowerPlant().getComponent(rc.getDestination()).read());
				} else {
					System.out.println(geng.getPowerPlant().getComponent(rc.getDestination()).getAttribute(rc.getAttribute()));
				}
			} catch (Exception e) {
				System.out.println(e);
			}
		
		} else if (command.equals("list")) {
			System.out.println(geng.getPowerPlant().getNameList());
		
		} else if (command.equals("print")) {
			geng.getPowerPlant().print();
		}
		else {
			System.out.println("Command not found. Try help");
		}

	}
	
	public void run() {
		System.out.println("Welcome to Bunny-Attack 3000!\n\n\n" +
						   "You step up to the terminal, and place your thumb on the scanner. You see the words:\n" +
				           "Helsetta Power Plant Online.\n" +
				           "User not recognised, please run name command.\n" +
				           "Alternatively, type help.");
		
		InputStreamReader isr = new InputStreamReader(System.in);
		BufferedReader br = new BufferedReader(isr);
		
		try {
			// run as long as the game engine is running
			while(!geng.isStopped()) {
				String command = br.readLine();
				processCommand(command);
			}
		} catch (Exception e) {
			System.out.println("Exception " + e + " caught");
		}
	}
}
